﻿using System;

namespace SimpleForum.Utils
{
    public static class DateTimeHelper
    {
        public static string TimeAgo(this DateTime From, bool AgoSuffix = true)
        {
            var TS = new TimeSpan(DateTime.UtcNow.Ticks - From.Ticks);
            string Suffix = (AgoSuffix ? " ago" : "");
            double Delta = TS.TotalSeconds;

            const int SECOND = 1;
            const int MINUTE = 60 * SECOND;
            const int HOUR = 60 * MINUTE;
            const int DAY = 24 * HOUR;
            const int MONTH = 30 * DAY;

            if (Delta < 0) return "not yet";
            if (Delta < 1 * MINUTE) return TS.Seconds == 1 ? "one second" + Suffix : TS.Seconds + " seconds" + Suffix;
            if (Delta < 2 * MINUTE) return "a minute" + Suffix;
            if (Delta < 45 * MINUTE) return TS.Minutes + " minutes" + Suffix;
            if (Delta < 90 * MINUTE) return "an hour" + Suffix;
            if (Delta < 24 * HOUR) return TS.Hours + " hours" + Suffix;
            if (Delta < 48 * HOUR) return "yesterday";
            if (Delta < 30 * DAY) return TS.Days + " days" + Suffix;

            if (Delta < 12 * MONTH)
            {
                int Months = Convert.ToInt32(Math.Floor((double)TS.Days / 30));
                return Months <= 1 ? "one month" + Suffix : Months + " months" + Suffix;
            }
            else
            {
                int Years = Convert.ToInt32(Math.Floor((double)TS.Days / 365));
                return Years <= 1 ? "one year" + Suffix : Years + " years" + Suffix;
            }
        }
    }
}